using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using BSDS.Core.Model;
using BSDS.Core.Model.Data;

namespace BSDS.Core.Data.Local.Xml.Parsing
{
    public class XmlEntityParser
    {
        public EntityValue FromXml(AttributeInfo[] attributeInfos, XElement xmlEntity)
        {
            var attributeValues = new List<AttributeValue>();

            foreach (var attributeInfo in attributeInfos)
            {
                var matchingElement = xmlEntity.Descendants(XName.Get(attributeInfo.Name)).FirstOrDefault();

                if(matchingElement == null && attributeInfo.Datatype != "string")
                {
                    throw new Exception("Cannot find attribute: " + attributeInfo.Name + " for entity: " + xmlEntity.Value);
                }

                var attributeValue = string.Empty;
                if (matchingElement != null)
                {
                    attributeValue = matchingElement.Value;
                }

                attributeValues.Add(new AttributeValue(attributeInfo, attributeValue));
            }

            return new EntityValue(attributeValues);
        }
    }
}